﻿using System;
using System.IO;
using System.Web;

using BlueCMS.Core.Entities;

namespace BlueCMS.Core
{
    public class CmsApplication : HttpApplication
    {
        const string ORIGINAL_URL_KEY = "BlueCMS.Core.CmsApplication.ORIGINAL_URL_KEY";
        const string NODE_KEY = "BlueCMS.Core.CmsApplication.NODE_KEY";
        const string WEBSITE_KEY = "BlueCMS.Core.CmsApplication.WEBSITE_KEY";
        const string USER_KEY = "BlueCMS.Core.CmsApplication.USER_KEY";

        public CmsApplication()
        {
            this.BeginRequest += new EventHandler(CmsApplication_BeginRequest);
            this.PreRequestHandlerExecute += new EventHandler(CmsApplication_PreRequestHandlerExecute);
        }

        void CmsApplication_BeginRequest(object sender, EventArgs e)
        {
            string originalUrl = Context.Request.Url.AbsolutePath;

            if (originalUrl.EndsWith("/"))
            {
                originalUrl = String.Format("{0}index.cms", originalUrl);
            }

            Context.Items[ORIGINAL_URL_KEY] = originalUrl;

            string filePath = Server.MapPath(originalUrl);
            if (File.Exists(filePath))
            {
                return;
            }

            if (originalUrl.EndsWith(".axd"))
            {
                return;
            }

            Context.RewritePath("~/Dispatch.ashx", false);
        }

        void CmsApplication_PreRequestHandlerExecute(object sender, EventArgs e)
        {
            Context.RewritePath((string)Context.Items[ORIGINAL_URL_KEY]);
        }

        public static string CmsOriginalUrl
        {
            get { return HttpContext.Current.Items[ORIGINAL_URL_KEY] as string; }
            set { HttpContext.Current.Items[ORIGINAL_URL_KEY] = value; }
        }

        public static Node CmsNode
        {
            get { return HttpContext.Current.Items[NODE_KEY] as Node; }
            set { HttpContext.Current.Items[NODE_KEY] = value; }
        }

        public static Website CmsWebsite
        {
            get { return HttpContext.Current.Items[WEBSITE_KEY] as Website; }
            set { HttpContext.Current.Items[WEBSITE_KEY] = value; }
        }

        public static User CmsUser
        {
            get { return HttpContext.Current.Items[USER_KEY] as User; }
            set { HttpContext.Current.Items[USER_KEY] = value; }
        }
    }
}
